﻿using System;
using System.IO;
using System.IO.Packaging;
using System.Web.UI;
using Microsoft.SharePoint;
using OfficeOpenXml;
using System.Text;

namespace Eneta.Portal.UiActions.Pages
{
    public class DownloadAsExcel : Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var listGuid = new Guid(Request.QueryString["list"]);
            var list = SPContext.Current.Web.Lists[listGuid];
            if (list == null)
            {
                Response.Write("Cannot find list ");
                return;
            }

            var view = list.Views[new Guid(Request.QueryString["view"])];
            var items = list.GetItems(view);

            Response.Clear();
            Response.ContentType = "text/plain; charset=ISO-8859-1";
            Response.AddHeader("Content-disposition", "attachment; filename=results.csv");            
            
            for(var i = 0; i<view.ViewFields.Count; i++)
            {
                Response.Write("\"");
                Response.Write(Utf8ToIso(view.ViewFields[i]));
                Response.Write("\"");

                if(i<view.ViewFields.Count -1 )
                {
                    Response.Write(";");
                }
            }
            Response.Write("\r\n");

            foreach (SPListItem item in items)
            {
                for (var i = 0; i < view.ViewFields.Count; i++)
                {
                    var valAsObj = item[view.ViewFields[i]];
                    string value = string.Empty;
                    if (valAsObj != null)
                        value = valAsObj.ToString();

                    Response.Write("\"");
                    Response.Write(Utf8ToIso(value));
                    Response.Write("\"");
                    if (i < view.ViewFields.Count - 1)
                    {
                        Response.Write(";");
                    }
                }

                Response.Write("\r\n");
            }
            
            //Response.Write("</Table></Worksheet></Workbook>");
            Response.Flush();
            Response.End();
        }

        private string Utf8ToIso(string text)
        {
            var fromEnc = Encoding.UTF8;
            var toEnc = Encoding.GetEncoding("ISO-8859-1");
            var fromBytes = fromEnc.GetBytes(text);
            var convBytes = Encoding.Convert(fromEnc, toEnc, fromBytes);
            return toEnc.GetString(convBytes);
        }
    }
}
